import {
  CanActivate,
  ExecutionContext,
  HttpException,
  HttpStatus,
  Injectable,
} from '@nestjs/common';
import * as moment from 'moment';
import { CodeEnum, CodeMessage } from 'src/constants/code';
import { TokenEntity } from './entities/token.entity';

@Injectable()
// 拦截器
export class AuthGuard implements CanActivate {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    // 获取token
    const token = context.switchToRpc().getData().headers.token;
    if (token) {
      // 根据token查询是否过期
      const tokenInfo = await TokenEntity.findOne({
        where: { token },
        select: ['userId', 'expireTime'],
      });
      // 是否过期
      const isExpire: boolean = moment(tokenInfo?.expireTime).isAfter(new Date());
      if (tokenInfo && isExpire) {
        return true;
      } else {
        throw new HttpException(
          JSON.stringify({
            code: CodeEnum.TOKEN_ERROR,
            message: CodeMessage[CodeEnum.TOKEN_ERROR],
          }),
          HttpStatus.OK,
        );
      }
    }
    throw new HttpException(
      JSON.stringify({ code: CodeEnum.NO_TOKEN, message: CodeMessage[CodeEnum.NO_TOKEN] }),
      HttpStatus.OK,
    );
  }
}
